package com.dragon.graduation.project.controller;

import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dragon.config.exception.exception.GlobalException;
import com.dragon.graduation.finalDefense.entity.FinalDefenseEntity;
import com.dragon.graduation.finalDefense.service.FinalDefenseService;
import com.dragon.graduation.graduationMaterial.entity.GraduationMaterialEntity;
import com.dragon.graduation.graduationMaterial.service.GraduationMaterialService;
import com.dragon.graduation.midtermDefense.entity.MidtermDefenseEntity;
import com.dragon.graduation.midtermDefense.service.MidtermDefenseService;
import com.dragon.graduation.project.controller.dto.ProjectAddDTO;
import com.dragon.graduation.project.controller.dto.ProjectSearchDTO;
import com.dragon.graduation.project.controller.dto.ProjectUpdateDTO;
import com.dragon.graduation.project.controller.vo.ProjectVO;
import com.dragon.graduation.project.controller.vo.StudentProjectVO;
import com.dragon.graduation.project.entity.ProjectEntity;
import com.dragon.graduation.project.service.ProjectService;
import com.dragon.graduation.projectApplication.entity.ProjectApplicationEntity;
import com.dragon.graduation.projectApplication.service.ProjectApplicationService;
import com.dragon.graduation.projectProgress.entity.ProjectProgressEntity;
import com.dragon.graduation.projectProgress.service.ProjectProgressService;
import com.dragon.graduation.projectTeacher.entity.ProjectTeacherEntity;
import com.dragon.graduation.projectTeacher.service.ProjectTeacherService;
import com.dragon.graduation.proposalReport.entity.ProposalReportEntity;
import com.dragon.graduation.proposalReport.service.ProposalReportService;
import com.dragon.graduation.teacher.entity.TeacherEntity;
import com.dragon.graduation.teacher.service.TeacherService;
import com.dragon.graduation.user.controller.vo.UserVO;
import com.dragon.jwt.JwtUtil;
import com.dragon.results.page.ResultPage;
import com.dragon.results.result.HttpResult;
import com.dragon.util.MyPage;
import com.dragon.util.WrapperUtil;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 题目表 前端控制器
 * </p>
 *
 * @author dragon
 * @since 2025-02-28 21:19:40
 */
@RestController
@RequestMapping("/project")
@RequiredArgsConstructor
@Api(tags = "题目表 相关接口")
public class ProjectController {

    private final ProjectService projectService;
    private final TeacherService teacherService;
    private final ProjectTeacherService projectTeacherService;
    private final ProjectApplicationService projectApplicationService;
    private final ProposalReportService proposalReportService;
    private final MidtermDefenseService midtermDefenseService;
    private final FinalDefenseService finalDefenseService;
    private final GraduationMaterialService graduationMaterialService;
    private final ProjectProgressService projectProgressService;

    @PostMapping("add")
    @ApiOperation("1]题目表添加")
    @ApiOperationSupport(order = 1)
    public HttpResult<String> add(@RequestBody ProjectAddDTO addDTO) {
        ProjectEntity entity = ProjectAddDTO.to(addDTO, ProjectEntity.class);
        entity.setReleaseTime(LocalDateTime.now());
        UserVO userVO = JwtUtil.parseToken(JwtUtil.getTokenFromRequest(), UserVO.class);
        Assert.isFalse(userVO.getRole() != 3, () -> new GlobalException("您非教师，不能发布题目"));
        TeacherEntity teacher = teacherService.getByUserId(userVO.getId());
        entity.setTeacherId(teacher.getId());
        projectService.save(entity);
        ProjectTeacherEntity teacherEntity = ProjectTeacherEntity.builder()
                .projectId(entity.getId())
                .teacherId(teacher.getId())
                .build();
        projectTeacherService.save(teacherEntity);
        return HttpResult.ok("添加成功");
    }

    @PostMapping("update")
    @ApiOperation("2]题目表修改")
    @ApiOperationSupport(order = 2)
    public HttpResult<String> update(@RequestBody ProjectUpdateDTO updateDTO) {
        ProjectEntity entity = projectService.getById(updateDTO.getId());
        Assert.isFalse(ObjectUtils.isEmpty(entity), () -> new GlobalException("要修改的数据不存在"));
        entity = ProjectUpdateDTO.to(updateDTO, ProjectEntity.class);
        projectService.updateById(entity);
        return HttpResult.ok("修改成功");
    }

    @PostMapping("search")
    @ApiOperation("3]题目表分页查询")
    @ApiOperationSupport(order = 3)
    public HttpResult<ResultPage<List<ProjectVO>>> search(@RequestBody ProjectSearchDTO searchDTO) {
        QueryWrapper<ProjectEntity> queryWrapper = WrapperUtil.constructWrapper(searchDTO, ProjectEntity.class);

        Page<ProjectEntity> entityPage = MyPage.setPage(ProjectEntity.class, searchDTO.getPage());
        Page<ProjectEntity> page = projectService.page(entityPage, queryWrapper);
        ResultPage<List<ProjectVO>> resultPage = MyPage.copyPage(page, ProjectVO.class);
        if (!CollectionUtils.isEmpty(page.getRecords())) {
            List<Integer> collected = page.getRecords().stream().map(ProjectEntity::getTeacherId).collect(Collectors.toList());
            List<TeacherEntity> entityList = teacherService.listByIds(collected);
            entityList.forEach(entity -> {
                for (ProjectVO record : resultPage.getRecords()) {
                    if (record.getTeacherId().equals(entity.getId())) {
                        record.setTeacherName(entity.getName());
                    }
                }
            });
        }
        return HttpResult.okForData(resultPage);
    }

    @PostMapping("delete")
    @ApiOperation("4]题目表删除")
    @ApiOperationSupport(order = 4)
    public HttpResult<String> delete(@RequestBody List<Integer> idList) {
        projectService.removeByIds(idList);
        //删除题目与教师关系
        projectTeacherService.lambdaUpdate()
                .in(ProjectTeacherEntity::getProjectId, idList)
                .remove();
        //删除关于该题目的选题申请
        projectApplicationService.lambdaUpdate()
                .in(ProjectApplicationEntity::getProjectId, idList)
                .remove();
        //删除关于该题目的开题报告
        proposalReportService.lambdaUpdate()
                .in(ProposalReportEntity::getProjectId, idList)
                .remove();
        //删除关于该题目的中期答辩
        midtermDefenseService.lambdaUpdate()
                .in(MidtermDefenseEntity::getProjectId, idList)
                .remove();
        //删除关于该题目的终期答辩
        finalDefenseService.lambdaUpdate()
                .in(FinalDefenseEntity::getProjectId, idList)
                .remove();
        //删除关于该题目的毕业材料
        graduationMaterialService.lambdaUpdate()
                .in(GraduationMaterialEntity::getProjectId, idList)
                .remove();
        //删除关于该题目的进度
        projectProgressService.lambdaUpdate()
                .in(ProjectProgressEntity::getProjectId, idList)
                .remove();
        return HttpResult.ok("删除成功");
    }

    @GetMapping("student/project")
    @ApiOperation("5]获取当前用户所选择的题目")
    @ApiOperationSupport(order = 5)
    public HttpResult<List<StudentProjectVO>> getProject(){
        UserVO userVO = JwtUtil.parseToken(JwtUtil.getTokenFromRequest(), UserVO.class);
        List<StudentProjectVO> result=projectApplicationService.findByStudentId(userVO.getRoleId());
        return HttpResult.okForData(result);
    }
}
